<template>
  <view>
    <form @submit="formSubmit" @reset="formReset">
      <view class="uni-form-item uni-column input-item">
         <input class="uni-input" name="username" placeholder="账号" :value="userInfo.username"/>
      </view>
      <view class="uni-form-item uni-column input-item">
        <input class="uni-input" name="password" placeholder="密码" :value="userInfo.password"/>
      </view>
      <view class="uni-btn-v">
        <button form-type="submit" type="primary" size="small">登录</button>
        <button type="default" @click="toRegister" size="small">没账号，去注册</button>
      </view>
    </form>
  </view>
</template>

<script>
var  graceChecker = require("../../../common/graceChecker.js");
import { mapActions } from "vuex";
export default {
  name: 'login',
  data() {
    return {
      userInfo: {
        username: '',
        password: '',
      }
    }
  },
  methods: {
    ...mapActions(['userLogin']),
    formSubmit(e){
      //定义表单规则
      var rule = [
          {name:"username", checkType : "string", checkRule:"3,8",  errorMsg:"账号应为3-8个字符"},
          {name:"password", checkType : "string", checkRule:"5,12",  errorMsg:"密码应为5-12个字符"}
      ];
      //进行表单检查
      var formData = e.detail.value;
      var checkRes = graceChecker.check(formData, rule);
      if(checkRes){
          //通过vuex保存数据
          // uni.redirectTo({ url: "pages/tabBar/user/user" })
        this.userLogin(formData).then(res=>{
          if(res.code == 200) {
            uni.showToast({title:"登录通过!"});
            setTimeout(()=>{
              uni.switchTab({
                url: '/pages/tabBar/user/user',
                complete(e){
                  console.log(e)
                }
                // delta: 1
              })
            }, 200)
          }
        })
      }else{
        uni.showToast({ title: graceChecker.error, icon: "none" });
      }
    },
    toRegister() {
      uni.navigateTo({
        url: '/pages/tabBar/user/register',
        success: (e)=>{
          console.log(e)
        },
        complete: (e)=>{
          console.log('complete: ', e)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.input-item {
  width: 750rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  input {
    width: 90%;
  }
}
.uni-btn-v {
  width: 750rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  button {
    width: 95%;
    // &[type="primary"]{
    //   background: #007aff;
    // }
  }

}
</style>